<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.sort" style="width: 110px;margin-right:10px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="listQuery.userName" placeholder="请输入内容" style="width: 200px;margin-right:10px" class="filter-item">
        <template slot="prepend">用户名</template>
      </el-input>
      <el-input v-model="listQuery.nick" placeholder="请输入内容" style="width: 200px;margin-right:10px" class="filter-item">
        <template slot="prepend">昵称</template>
      </el-input>
      <el-select v-model="listQuery.status" clearable placeholder="用户状态" style="width: 120px;margin-right:10px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.searchType" placeholder="请选择查询的类型" style="width: 150px;margin-right:10px" class="filter-item">
        <el-option v-for="item in searchTypeOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="warning" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nick }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录Ip" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lastLoginIp }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lastLoginTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="QQ" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.qq }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" width="100px" align="center">
        <template slot-scope="{row}">
          <img :src="row.avatar+'?imageView2/1/w/80/h/80'" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusText | statusButtonStyle">
            {{ row.status | statusText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <template>
            <el-popconfirm
              title="这确定删除这条记录？"
              @onConfirm="handleDelete(row,$index)"
            >
              <el-button slot="reference" style="margin-left:10px;" size="mini" type="danger">
                删除
              </el-button>
            </el-popconfirm>
          </template>
        </template></el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" :page-sizes="[5, 10, 20, 30]" @pagination="getList" />

    <!-- 新增编辑对话框 -->
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='update'" label="密码" prop="password" type="password" disabled>
          <el-input v-model="temp.password" disabled type="password" />
        </el-form-item>
        <el-form-item v-else label="密码" prop="password">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="昵称" prop="nick">
          <el-input v-model="temp.nick" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="temp.qq" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validWords, validQQ, validEmail, validMobile } from '@/utils/validate' // 数据校验
import elDragDialog from '@/directive/el-drag-dialog'
import { getById, fetchList, createSysUser, updateSysUser, deleteOneSysUser } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves, elDragDialog },
  filters: {
    statusText(status) {
      const statusMap = {
        0: '禁用',
        1: '正常',
        2: '锁住'
      }
      return statusMap[status]
    },
    statusButtonStyle(text) {
      const statusMap = {
        '禁用': 'danger',
        '正常': 'success',
        '锁住': 'warning'
      }
      return statusMap[text]
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validWords(value)) {
        callback(new Error('用户名由6-20位的字母数字下划线组成！！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validWords(value) && this.dialogStatus === 'create') {
        callback(new Error('密码由6-20位的字母数字下划线组成！！'))
      } else {
        callback()
      }
    }
    const validateNick = (rule, value, callback) => {
      if (!/^.{3,10}$/.test(value)) {
        callback(new Error('昵称为3-10个字符！！'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('电话号码格式不合法！！'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('邮箱格式不合法！！'))
      } else {
        callback()
      }
    }
    const validateQq = (rule, value, callback) => {
      if (!validQQ(value)) {
        callback(new Error('QQ号格式不合法！！'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        sort: 'asc',
        userName: '',
        status: undefined,
        searchType: true
      },
      sortOptions: [{ label: 'ID 正序', key: 'asc' }, { label: 'ID 倒序', key: 'desc' }],
      searchTypeOptions: [{ label: '查询条件并集', key: false }, { label: '查询条件交集', key: true }],
      statusOptions: [{ label: '禁用', key: 0 }, { label: '正常', key: 1 }, { label: '锁住', key: 2 }],
      showReviewer: false,
      temp: {
        id: undefined,
        userName: 'lzpisnb',
        password: 'lzpisnb',
        nick: '隔壁老龙',
        mobile: '15115282455',
        email: 'longzipeng@foxmail.com',
        qq: '1739028870',
        status: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userName: [{ required: true, message: '', validator: validateUsername }],
        password: [{ required: true, message: '', validator: validatePassword }],
        nick: [{ required: true, message: '', validator: validateNick }],
        mobile: [{ required: true, message: '', validator: validateMobile }],
        email: [{ required: true, message: '', validator: validateEmail }],
        qq: [{ required: true, message: '', validator: validateQq }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'asc'
      } else {
        this.listQuery.sort = 'desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: 'lzpisnb',
        password: 'lzpisnb',
        nick: '隔壁老龙',
        mobile: '15115282455',
        email: 'longzipeng@foxmail.com',
        qq: '1739028870',
        status: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createSysUser(this.temp).then((response) => {
            if (response.code === '200') {
              this.$notify({
                title: '提示',
                message: response.message,
                type: 'success',
                duration: 2000
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(row) {
      getById(row.id).then((response) => {
        if (response.code === '200') {
          this.temp = Object.assign({}, response.data) // copy obj
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$notify({
            message: '该用户不存在！！',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSysUser(tempData).then((response) => {
            if (response.code === '200') {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '提示',
                message: response.message,
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row, $index) {
      deleteOneSysUser(row.id).then(response => {
        if (response.code === '200') {
          this.$notify({
            title: '提示',
            message: '删除成功！！',
            type: 'success',
            duration: 2000
          })
          this.list.splice($index, 1)
          this.total = this.list.length
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'userName', 'password', 'nick', 'mobile', 'email', 'qq', 'status']
        const filterVal = ['id', 'userName', 'password', 'nick', 'mobile', 'email', 'qq', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
  .user-avatar {
    width: 50px;
    height: 50px;
  }
</style>
